package com.dong.order.controller;

import com.dong.order.lb.ILoadBalancer;
import com.dong.springcloud.entities.CommonResult;
import com.dong.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author DJ
 * @description 消费者控制层
 * @date 2021/12/25 11:00 下午
 **/
@RestController
// @AllArgsConstructor
@Slf4j
public class OrderController {

    // public static final String PAYMENT_URL = "http://localhost:9001";
    /**
     * 负载均衡后不需要聚体的服务ip：port 服务名即可
     */
    public static final String PAYMENT_URL = "http://cloud-payment-service";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ILoadBalancer iLoadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        log.debug("消费者服务serverPort:{}", serverPort);
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @PostMapping("consumer/payment/insert")
    public CommonResult<Payment> insert(Payment payment) {
        log.debug("消费者服务serverPort:{}", serverPort);
        return restTemplate.postForObject(PAYMENT_URL + "/payment/insert/", payment, CommonResult.class);
    }

    /**
     * 测试RestTemplate#getForEntity()
     *
     * @author DJ
     * @date 8:06 下午 2022/1/3
     * @param  id
     * @return com.dong.springcloud.entities.CommonResult<com.dong.springcloud.entities.Payment>
     **/
    @GetMapping("consumer/payment/getEntity/{id}")
    public CommonResult<Payment> getPaymentEntityById(@PathVariable(value = "id") String id) {
        ResponseEntity<CommonResult> resultResponseEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (resultResponseEntity.getStatusCode().is2xxSuccessful()) {
            return resultResponseEntity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    @GetMapping("consumer/payment/lb")
    public String getPaymentLb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance serviceInstance = iLoadBalancer.chooseInstance(instances);
        if (serviceInstance == null) {
            return null;
        }
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    @GetMapping("consumer/payment/thread-countDownLatch")
    public void threadCountDownLatch() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        // 创建一个线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1));
        executor.submit(() -> {
            CommonResult forObject = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + "1", CommonResult.class);
            System.out.println(forObject.getMessage());
            latch.countDown();
        });
        executor.submit(() -> {
            ResponseEntity<CommonResult> resultResponseEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + "1", CommonResult.class);
            System.out.println(resultResponseEntity.getStatusCodeValue());
            latch.countDown();
        });
        latch.await();
        executor.shutdown();
    }
}
